package com.bookpavilion.chat.netty;

import com.alibaba.fastjson.JSON;
import com.bookpavilion.chat.SpringUtil;
import com.bookpavilion.chat.client.UserClient;
import com.bookpavilion.chat.dao.MessageDao;
import com.bookpavilion.chat.pojo.*;
import com.bookpavilion.chat.service.MessageService;
import com.rabbitmq.client.impl.ChannelN;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import util.IdWorker;

import java.util.*;

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

    //将所有与客户端连接的Channel交给ChannelGroup管理
    private static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        MessageDao messageDao = (MessageDao) SpringUtil.getBean(MessageDao.class);
        MessageService messageService = (MessageService) SpringUtil.getBean(MessageService.class);
        IdWorker idWorker = (IdWorker) SpringUtil.getBean(IdWorker.class);
        String content = msg.text();
        Channel currentChannel = ctx.channel();
        DataContent dataContent = JSON.parseObject(content, DataContent.class);
        Integer action = dataContent.getAction();
        if (action== MsgActionEnum.CONNECT.type){
            String fromId = dataContent.getMessage().getFrom().getId();
            UserChannelRel.put(fromId,currentChannel);
        }else if (action==MsgActionEnum.CHAT.type){
            Message message = dataContent.getMessage();
            String fromId = message.getFrom().getId();
            String toId = message.getTo().getId();
            UserClient userClient = (UserClient) SpringUtil.getBean(UserClient.class);
            LinkedHashMap<String, String> fromData = (LinkedHashMap<String, String>) userClient.findById(fromId).getData();
            LinkedHashMap<String, String> toData = (LinkedHashMap<String, String>) userClient.findById(toId).getData();
            User from = User.builder().id(fromData.get("id")).nick_name(fromData.get("nick_name")).head_pic(fromData.get("head_pic")).build();
            User to = User.builder().id(toData.get("id")).nick_name(toData.get("nick_name")).head_pic(toData.get("head_pic")).build();
            message.setId(idWorker.nextId()+"");
            message.setFrom(from);
            message.setTo(to);
            message.setStatus(0);
            message.setSendDate(new Date());
            message=messageDao.save(message);
            DataContent dataContentMsg = new DataContent();
            dataContentMsg.setMessage(message);
            Channel receiverChannel = UserChannelRel.get(message.getTo().getId());
            if (receiverChannel ==null){
                // TODO: 2021/7/6 receiverChannerl 为空表示接收方离线，需要推送消息（使用第三方）
            }else {
                Channel findChannel = users.find(receiverChannel.id());
                if (findChannel!=null){
                    // TODO: 2021/7/6 findChannel 不为空代表当前用户在线
                    receiverChannel.writeAndFlush(new TextWebSocketFrame(
                            JSON.toJSONString(dataContentMsg)
                    ));
                }else {
                    // TODO: 2021/7/6 用户离线需要消息推送
                }
            }
        }else if (action==MsgActionEnum.SIGNED.type){
            String msgIdsStr = dataContent.getExtend();
            String[] idsStr = msgIdsStr.split(",");
            List<String> ids = new ArrayList<>();
            Collections.addAll(ids,idsStr);
            if (ids!=null&&!ids.isEmpty()&&ids.size()>0){
                // TODO: 2021/7/6  更新签收状态
                messageService.updateMessListById(ids,1);
            }
        }else if (action==MsgActionEnum.KEEPALIVE.type){
            System.out.println("收到来自channel为[" + currentChannel + "]的心跳包...");
        }

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        users.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

        users.remove(ctx.channel());
        super.handlerRemoved(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
        users.remove(ctx.channel());
    }

    public ChannelGroup getUsersChannel(){
        return users;
    }

}
